package com.example.ymm.util;

import com.example.ymm.bo.YmUserDetails;
import com.example.ymm.exception.NoPermissionException;
import com.example.ymm.model.ResultCode;
import com.example.ymm.model.UserLogin;

import com.example.ymm.modules1.entity.my.user.DbUser;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtil {

    public static UserLogin getUserLogin(){
        YmUserDetails ymUserDetails =null;
        UserLogin pdUserLogin=null;
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            if (authentication instanceof AnonymousAuthenticationToken) {
                return null;
            }

            if (authentication instanceof UsernamePasswordAuthenticationToken) {
                ymUserDetails = (YmUserDetails) authentication.getPrincipal();
            }
        }
        if(UtilValidate.isEmpty(ymUserDetails)){
            throw new NoPermissionException(ResultCode.UNAUTHORIZED.getMessage());
        }
        pdUserLogin= ymUserDetails.getUserLogin();
        return pdUserLogin;
    }



     public static String getUserId(){
        UserLogin userLogin = getUserLogin();
         String userId=null;
        if(UtilValidate.isNotEmpty(userLogin)){
            userId=userLogin.getId();
        }
        return userId;
    }


    public static String getUserNickName(){
        String userNickName="";
        UserLogin userLogin = getUserLogin();
        DbUser dbUser = userLogin.getDbUser();
        if(UtilValidate.isNotEmpty(dbUser)){
            userNickName= dbUser.getUserName();
        }
        return userNickName;
    }

}
